// https://uniapp.dcloud.net.cn/tutorial/platform.html
// APP-PLUS App
// APP-PLUS-NVUE或APP-NVUE App nvue 页面
// APP-ANDROID App Android 平台 仅限 uts文件
// APP-IOS App iOS 平台 仅限 uts文件
// H5 H5
// MP-WEIXIN 微信小程序
// MP-ALIPAY 支付宝小程序
// MP-BAIDU 百度小程序
// MP-TOUTIAO 抖音小程序
// MP-LARK 飞书小程序
// MP-QQ QQ小程序
// MP-KUAISHOU 快手小程序
// MP-JD 京东小程序
// MP-360 360小程序
// MP 微信小程序/支付宝小程序/百度小程序/抖音小程序/飞书小程序/QQ小程序/360小程序
// QUICKAPP-WEBVIEW 快应用通用(包含联盟、华为)
// QUICKAPP-WEBVIEW-UNION 快应用联盟
// QUICKAPP-WEBVIEW-HUAWEI 快应用华为
//

import _dayjs from 'dayjs'
import utc from 'dayjs/plugin/utc'
import isBetween from 'dayjs/plugin/isBetween'
import { getRect as _getRect } from '@/uni_modules/wot-design-uni/components/common/util'

_dayjs.extend(utc)
_dayjs.extend(isBetween)

export const getRect = _getRect
export const dayjs = _dayjs

export const getPlatform = () => {
  let platForm
  // #ifdef APP-PLUS || APP-NVUE || APP-PLUS-NVUE
  platForm = 'APP'
  // #endif
  // #ifdef H5
  platForm = 'H5'
  // #endif
  // #ifdef MP-WEIXIN
  platForm = 'MP-WEIXIN'
  // #endif
  // #ifdef MP-ALIPAY
  platForm = 'MP-ALIPAY'
  // #endif
  // #ifdef MP-BAIDU
  platForm = 'MP-BAIDU'
  // #endif
  // #ifdef MP-TOUTIAO
  platForm = 'MP-TOUTIAO'
  // #endif
  // #ifdef MP-LARK
  platForm = 'MP-LARK'
  // #endif
  // #ifdef MP-QQ
  platForm = 'MP-QQ'
  // #endif
  // #ifdef MP-KUAISHOU
  platForm = 'MP-KUAISHOU'
  // #endif
  // #ifdef MPJD-
  platForm = 'MP-JD'
  // #endif
  // #ifdef MP-360
  platForm = 'MP-360'
  // #endif
  // #ifdef QUICKAPP-WEBVIEW
  platForm = 'QUICKAPP-WEBVIEW'
  // #endif
  // #ifdef QUICKAPP-WEBVIEW-UNION
  platForm = 'QUICKAPP-WEBVIEW-UNION'
  // #endif
  // #ifdef QUICKAPP-WEBVIEW-HUAWEI
  platForm = 'QUICKAPP-WEBVIEW-HUAWEI'
  // #endif
  return platForm
}
//判断ios和安卓
export const checkDeviceType = () => {
  return new Promise((resolve, reject) => {
    uni.getSystemInfo({
      success: (res) => {
        const platform = res.platform.toLowerCase()
        if (platform === 'ios') {
          resolve('iOS')
        } else if (platform === 'android') {
          resolve('Android')
        } else {
          reject('Unknown')
        }
      },
      fail: (err) => {
        reject(err)
      },
    })
  })
}
// 清除对象中值不存在的键
export const objectNilClean = (obj) => {
  const newObj = clone(obj)
  delete newObj._X_ROW_KEY
  Object.keys(newObj).forEach(e => {
    if (isNil(newObj[e])) {
      delete newObj[e]
    }
  })
  return newObj
}
// 清除对象中值为空的键
export const objectClean = (obj) => {
  const newObj = clone(obj)
  delete newObj._X_ROW_KEY
  Object.keys(newObj).forEach(e => {
    if (isNilOrEmpty(newObj[e])) {
      delete newObj[e]
    }
  })
  return newObj
}

export const parseTableName = (tableName = '') => {
  let schema
  let table = tableName
  if (tableName.includes('.') && tableName.split('.').length > 1) {
    schema = tableName.split('.')[0]
    table = tableName.split('.')[1]
  }
  return { schema, table }
}

//数组扁平化（树状数组转普通数组）
export const treeToFlat = (arr, str = 'children') => {
  return arr.reduce((result, item) => {
    return result.concat(item, (Array.isArray(item[str]) ? treeToFlat(item[str]) : []))
  }, [])
}

// Tab页中的路径，请根据自己项目实际情况进行修改
const tabBarUrl = ['/pages/index']
//路由跳转
export function navTo(url, callback = undefined) {
  let newUrl = url
  if (url[0] === '/') { // 过滤首位的 /
    newUrl = url.substring(1)
  }
  const pathname = newUrl.split('?')[0]
  const params = newUrl.split('?')[1]
  const page = getCurrentPages()
  const index = page.findIndex(item => item.route === pathname)
  // 如果是Tab中的链接，直接跳转
  if (tabBarUrl.includes(pathname)) {
    uni.switchTab({
      url,
      success: () => {
        callback && callback()
      },
    })
    return
  }
  if (index !== -1) { // 在页面栈中找到时
    const step = page.length - 1 - index
    if (step === 0) {
      uni.redirectTo({
        url,
        success: () => {
          callback && callback()
        },
      })
    } else {
      if (params) {
        uni.redirectTo({
          url,
          success: () => {
            callback && callback()
          },
        })
        return
      }
      uni.navigateBack({ delta: step })
      callback && callback()
    }
    return
  }
  // 否则就直接跳转
  uni.navigateTo({
    url,
    success: () => {
      callback && callback()
    },
  })
}
//跳转tabbar页面，并刷新数据
export function reLanchTo(url) {
  uni.reLaunch({ url })
}
//返回上一级页面
export const goBack = (delta = 1) => {
  uni.navigateBack({ delta })
}
export const goHome = () => {
  navTo('/pages/index')
}
//是否为json串
export const isJSON = (str) => {
  if (typeof str == 'string') {
    try {
      let obj = JSON.parse(str)
      if (typeof obj == 'object' && obj) {
        return true
      } else {
        return false
      }

    } catch (e) {
      return false
    }
  }
}

export const oneToTwoArray = (list) => {
  let arrayTwo = Object.values(list.reduce((res, item) => {
    res[item.id] ? res[item.id].push(item) : res[item.id] = [item]
    return res
  }, {}))
  let data = []
  arrayTwo.forEach((nowItem) => {
    let obj = {}
    obj.title = nowItem[0].content
    obj.options = nowItem
    data.push(obj)
  })
  return data
}

//处理距离转换
export const formatDistance = (distance) => {
  if (distance >= 1000) {
    const kilometers = Math.round((distance / 1000) * 100) / 100
    return `${kilometers}km`
  } else {
    return `${Math.round(distance * 100) / 100}m`
  }
}

export const formatTime = (date, type) => {
  if (!date) {
    return
  }
  return _dayjs(date).utc().local().format(type)
}

export const checkLocationPermission = () => {
  return new Promise((resolve, reject) => {
    uni.getSetting({
      success(res) {
        if (res.authSetting['scope.userLocation']) {
          resolve(true)
        } else {
          resolve(false)
        }
      },
      fail(err) {
        reject(err)
      },
    })
  })
}

export function rpxToPx(rpx) {
  return uni.upx2px(rpx)
}

export function pxToRpx(px) {
  let scale = uni.upx2px(100) / 100
  return px / scale
}
